package com.qihunet.tplus.productimport.controller;

import com.qihunet.tplus.productimport.Service.CostAllocationOrderService;
import com.qihunet.tplus.productimport.entity.CostAllocationOrder;
import com.qihunet.tplus.productimport.entity.CostAllocationOrderDetails;
import com.qihunet.tplus.productimport.utils.ExcelComponent;
import com.qihunet.tplus.productimport.utils.ResultCode;
import com.qihunet.tplus.productimport.utils.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Controller
@RequestMapping("interface")
public class InterfaceController {

    @Autowired
    private CostAllocationOrderService costAllocationOrderService;

    @Autowired
    private ExcelComponent excelComponent;

    /**
     * 上传页面
     * @return
     */
    @GetMapping(value = "upload")
    public String upload() {
        return "/fileupload";
    }

    /**
     * 文件上传具体实现方法（单文件上传）
     *
     * @param file
     * @return
     *
     * @create 2017年3月11日
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file, RedirectAttributes attributes) {

        ResultInfo<CostAllocationOrder> resultInfo=new ResultInfo<>();
        resultInfo.setResultCode(ResultCode.ERROR);
        if (!file.isEmpty()) {
            try {
                // 这里只是简单例子，文件直接输出到项目路径下。
                // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
                // 还有关于文件格式限制、文件大小限制，详见：中配置。
                File targetFile=new File(file.getOriginalFilename());

                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(targetFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                //文件类型
                String excelType = file.getOriginalFilename()
                        .substring(file.getOriginalFilename().length() - 4)
                        .toUpperCase();
                Map<String,Object> excelMap= excelComponent.uploadFileDataToDB(targetFile,excelType);

                if((Boolean) excelMap.get("result")){
                    resultInfo.setResultCode(ResultCode.SUCCESS);
                    resultInfo= costAllocationOrderService.saveCostAllocationOrderInfo(excelMap);
                    if(resultInfo.getResultCode()==ResultCode.SUCCESS){
                        costAllocationOrderService.updateCostAllocationOrderDetailsInfo((List<CostAllocationOrderDetails>)excelMap.get("orderData"),resultInfo.getData().getId());
                    }
                }else{
                    resultInfo.setErrorMessage("导入失败,"+excelMap.get("message").toString());

                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                resultInfo.setErrorMessage("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                resultInfo.setErrorMessage("上传失败," + e.getMessage());
            }catch (RuntimeException ex){
                ex.printStackTrace();
                resultInfo.setErrorMessage("上传失败," + ex.getMessage());
            }
        } else {
            resultInfo.setErrorMessage("上传失败，因为文件是空的.");
        }
        attributes.addFlashAttribute("msg",resultInfo.getResultCode()==ResultCode.SUCCESS?"数据导入成功，请在T+系统中查看":resultInfo.getErrorMessage());
        return "redirect:/interface/upload";
    }



    /**
     * 获取所有的产品成本分配表信息
     * @return
     */
    @ResponseBody
    @RequestMapping("getAllCostAllocationOrder")
    public List<CostAllocationOrder> getAllCostAllocationOrder(){
        return  costAllocationOrderService.getList();
    }
}
